package com.chimm.web;

import com.chimm.dto.Exposer;
import com.chimm.dto.SeckillExecution;
import com.chimm.dto.SeckillResult;
import com.chimm.entity.Seckill;
import com.chimm.enums.SeckillStateEnum;
import com.chimm.excetion.RepeatKillException;
import com.chimm.excetion.SeckillCloseException;
import com.chimm.excetion.SeckillException;
import com.chimm.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 秒杀商品Controller
 */
@Controller
@RequestMapping("/seckill")  // uri: /模块/资源/{id}/细分  /seckill/list
public class SeckillController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 注入service
    @Autowired
    private SeckillService seckillService;

    /**
     * 获取秒杀商品列表
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(Model model) {
        // list.jsp + model = ModelAndView

        // 获取列表页
        List<Seckill> list = seckillService.getSeckkillList();
        model.addAttribute("list", list);

        return "list"; // WEB-INF/jsp/list.jsp
    }

    /**
     * 通过id获取详细的秒杀商品
     * @param seckillId 商品ID
     * @return
     */
    @RequestMapping(value = "/{seckillId}/detail",method = RequestMethod.GET)
    public String detail(@PathVariable("seckillId") Long seckillId, Model model) {
        // 如果传入的商品ID为空，则让浏览器跳转商品列表页面
        if (seckillId == null) {
            return "redirect:/seckill/list";
        }
        // 调用service服务，查询秒杀商品
        Seckill seckill = seckillService.getById(seckillId);

        // 对商品进行非空判断
        if (seckill == null) {
            // 如果商品不存在，请求转发到商品别表
            return "forward:/seckill/list";
        }

        model.addAttribute("seckill", seckill);

        return "detail";
    }


    // ajax json

    /**
     * 暴露秒杀地址
     * @param seckillId 秒杀商品ID
     * @return
     */
    @RequestMapping(value = "/{seckillId}/exposer",
                    method = RequestMethod.POST,
                    produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public SeckillResult<Exposer> exposer(@PathVariable("seckillId") Long seckillId){
        // 统一返回的json格式为seckillResult
        SeckillResult<Exposer> result ;
        try {
            // 1. 调用Service，返回暴露秒地址对象
            Exposer exposer = seckillService.exportSeckillUrl(seckillId);

            // 2.如果放回没报错，证明结果正在秒杀时间段内，将对象封装为SeckillResult对象
            result = new SeckillResult<Exposer>(true,exposer);
        } catch (Exception e) {
            // 2. 如果报错，则证明不再秒杀时间段内，打印错误日志，并返回给前台false
            logger.error(e.getMessage(),e);
            result = new SeckillResult<Exposer>(false, e.getMessage());
        }
        return result;
    }

    /**
     * 执行秒杀
     * @return
     */
    @RequestMapping(value = "/{seckillId}/{md5}/execution",
                    method = RequestMethod.POST,
                    produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId") Long seckillId,
                                                   @PathVariable("md5") String md5,
                                                   @CookieValue(value = "killPhone",required = false) Long phone) {
        // 对用户传递的数据进行判断
        if (phone == null) {
            return new SeckillResult<SeckillExecution>(false, "未注册");
        }

        try {
            /*// 统一返回的json格式为seckillResult
            SeckillResult<SeckillExecution> result;*/

            // 1.调用service，
            SeckillExecution execution = seckillService.executeSeckill(seckillId,phone ,md5);

            // 2.成功执行秒杀 返回的结果对象
            return new SeckillResult<SeckillExecution>(true,execution);
        } catch (SeckillCloseException e){
            // 2.1 执行秒杀失败，不再秒杀时间范围内
            SeckillExecution seckillExecution = new SeckillExecution(seckillId, SeckillStateEnum.END);
            return new SeckillResult<SeckillExecution>(true, seckillExecution);
        } catch (RepeatKillException e){
            // 2.2 执行秒杀失败，重复秒杀
            SeckillExecution execution = new SeckillExecution(seckillId,SeckillStateEnum.REPEAT_KILL);
            return new SeckillResult<SeckillExecution>(true, execution);
        } catch (SeckillException e) {
            // 2.3 其他所有的错误，都归结为内部错误，是不允许的错误
            // 打印日志
            logger.error(e.getMessage(), e);
            SeckillExecution seckillExecution = new SeckillExecution(seckillId, SeckillStateEnum.INNER_ERROR);
            return new SeckillResult<SeckillExecution>(true, seckillExecution);
        }
    }

    /**
     * 获取系统时间
     * @return
     */
    @RequestMapping(value = "/time/now",method = RequestMethod.GET)
    @ResponseBody
    public SeckillResult<Long> time() {
        Date now = new Date();
        return new SeckillResult<Long>(true, now.getTime());
    }
}
